package com.wswy.wzcx.ui.fragment;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.api.ConfigsKt;
import com.wswy.wzcx.model.PaymentOrder;
import com.wswy.wzcx.model.wzdb.WzdbOrderInfo;
import com.wswy.wzcx.module.InternalMsgCodeKt;
import com.wswy.wzcx.module.base.PayViewModel;
import com.wswy.wzcx.module.base.PayViewModel.OrderPayResult;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.activity.ModuleActivity;
import com.wswy.wzcx.ui.dialog.FullHintAlertDialog;
import com.wswy.wzcx.ui.other.CloseDelegate;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.web.WebViewActivity;
import java.util.Map;


/**
 * Created by wangduheng26 on 2018/3/23.
 * wangduheng26@gmail.com
 */

public class WZDBSubmitFragment extends PayFragment {
    //
    public static final String TAG = "WZDBSubmitFragment";
    private TextView tvCount;
    private TextView tvFine;
    private TextView tvLateFee;
    private TextView tvFree;
    CloseDelegate delegate;

    private WzdbOrderInfo orderInfo;

    private PayViewModel payViewModel;

    public static WZDBSubmitFragment newInstance(WzdbOrderInfo orderInfo) {

        Bundle args = new Bundle();
        args.putParcelable("data", orderInfo);
        WZDBSubmitFragment fragment = new WZDBSubmitFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static WZDBSubmitFragment newInstance(String orderNo) {

        Bundle args = new Bundle();
        args.putString("orderNo", orderNo);
        WZDBSubmitFragment fragment = new WZDBSubmitFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey("data"))
            orderInfo = arguments.getParcelable("data");
        if(orderInfo == null && arguments != null){
            orderNo = arguments.getString("orderNo");
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_issues, menu);
        MenuItem item = menu.findItem(R.id.action_issues);
        SpannableString s = new SpannableString(item.getTitle());
        s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.colorPrimary)), 0, s.length(), 0);
        item.setTitle(s);
        super.onCreateOptionsMenu(menu, inflater);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_issues) {
            WebViewActivity.startWebview(getContext(),ConfigsKt.H5_CJWT_WZDB());
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void createView(Context context, LinearLayout layout) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.wzdb_submit_layout, layout, true);
//        ButterKnife.bind(this,inflate);
        FrameLayout frame = inflate.findViewById(R.id.frame);
        frame.addView(createPayStyleView(getContext(), frame), LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        TextView tvProtocol = inflate.findViewById(R.id.tv_protocol);
        tvProtocol.setText(Html.fromHtml(getString(R.string.agree_pay_protocol)));
        tvProtocol.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewActivity.startWebview(v.getContext(), ConfigsKt.H5_PRO_WZDB());
            }
        });
        tvCount = inflate.findViewById(R.id.tv_total_count);
        tvFine = inflate.findViewById(R.id.tv_total_fine);
        tvFree = inflate.findViewById(R.id.tv_total_free);
        tvLateFee = inflate.findViewById(R.id.tv_late_free);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        payViewModel = provideViewModel(PayViewModel.class);
        payViewModel.onCreate();

        if(orderInfo==null){

            requestOrder(orderNo);

        }else {
            updateView();
        }



        payViewModel.getOrderPayResultLiveData().observe(this, new Observer<OrderPayResult>() {
            @Override
            public void onChanged(@Nullable OrderPayResult orderPayResult) {

                if (orderPayResult != null){

                    if (orderPayResult.getStatus()){
                        //支付成功
                        onPaySuccess();
                    }else {
                        onPayFail();
                    }

                }

            }
        });

        delegate = new CloseDelegate(this,InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD);
    }


    private void updateView(){
        if(orderInfo != null) {
            tvCount.setText(String.valueOf(orderInfo.getCount()));

            //tvFine.setText(getString(R.string.amount_args, orderInfo.getPenalty()));
            //tvFree.setText(getString(R.string.amount_args, orderInfo.getServiceFee()));
            //tvLateFee.setText(getString(R.string.amount_args, orderInfo.getLateFee()));


            tvFine.setText(orderInfo.getPenalty());
            tvFree.setText(orderInfo.getServiceFee());
            tvLateFee.setText(orderInfo.getLateFee());
            tvPayMuch.setText(getString(R.string.str_fkdj_params, orderInfo.getMoney()));
        }
    }


    private void requestOrder(String orderNo){
        Api.get().getWZDBOrderInfo(orderNo).subscribe(new ProgressDialogObserver<WzdbOrderInfo>(getContext()){

            @Override
            protected void onApiResult(@Nullable WzdbOrderInfo wzdbOrderInfo) {
                if(wzdbOrderInfo != null){
                    orderInfo = wzdbOrderInfo;
                    updateView();
                }else {
                    ToastUtils.showText("获取订单信息失败，请稍后重试");
                }
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                toastErrorMsg(result);
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tvPay) {

            new FullHintAlertDialog(getContext())
                .setDelayNext(5)
                .setDialogMessage(R.string.wzdb_pay_hint1,R.string.wzdb_pay_hint2)
                .setLeftText(R.string.think_about,null)
                .setRightText(R.string.continue_pay, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doPay();
                    }
                })
                .show();
        }
    }


    private void doPay(){
        StatTools.sendClick(getContext(), StatisticsId.clickWZDB_Pay);
        final String payOrderNo = orderInfo.getOrderNo();

        Api.get().payWZDB(payOrderNo,String.valueOf(payStyle),null,null)
            .subscribe(new ProgressDialogObserver<PaymentOrder>(getContext(), "提示", "正在获取支付信息") {

                @Override
                protected void onApiResult(@Nullable PaymentOrder paymentOrder) {
                    if (paymentOrder != null && !TextUtils.isEmpty(paymentOrder.getPay())) {
                        //保存支付
                        paymentOrder.setPayStyle(payStyle);
                        paymentOrder.setBizType("wzdb");
                        if (TextUtils.isEmpty(paymentOrder.getOrderNo())){
                            paymentOrder.setOrderNo(payOrderNo);
                        }

                        payViewModel.startPay(requireActivity(),paymentOrder);

                    }else {
                        ToastUtils.showText("获取支付信息出现异常");
                    }
                    orderNo = orderInfo.getOrderNo();
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                }
            });
    }


    @Override
    public void onDestroy() {
        if (delegate != null)
            delegate.onDestroy();
        super.onDestroy();
    }

    @Override
    public String getFragmentTitle() {
        return "提交订单";
    }

    private void onPaySuccess() {
        if (!TextUtils.isEmpty(orderNo)) {
//            Api.get().fetchOrderNeedParams(orderNo)
//                    .subscribe(new ApiOptionalResultObserver<List<OrderNoNeedParam>>() {
//
//                        @Override
//                        protected void onApiResult(@Nullable List<OrderNoNeedParam> params) {
//                            if (params != null && !params.isEmpty())
//                                UpLoadActivity.Companion.startUploadPage(getContext(), orderNo, params.toArray(new OrderNoNeedParam[params.size()]));
//                        }
//
//                        @Override
//                        protected void onApiError(@Nullable BaseResult result) {
//                            toastErrorMsg(result);
//                        }
//                    });

            RxBus.getDefault().postWithCode(InternalMsgCodeKt.UPLOAD_COMPLETE_WDZD, "");
            RxBus.getDefault().postWithCode(InternalMsgCodeKt.ORDER_STATUS_CHANGED, "");


            ToastUtils.showText("支付成功");

            Context context = getContext();
            if (context != null){
                Intent targetIntent = ModuleActivity.getTargetIntent(context, FKDJResultFragment.TAG);
                targetIntent.putExtra("data", true);
                context.startActivity(targetIntent);
            }

          finish();

        } else {
            ToastUtils.showText("订单号为空");
        }
    }

    private void onPayFail() {

    }

//    @Override
//    public boolean onBackPress() {
//        showBackDialog();
//        return true;
//    }

    private void showBackDialog(){
        new FullHintAlertDialog(getContext())
            .setDialogMessage(R.string.wzdb_back_hint)
            .setLeftText(R.string.reject_next, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            })
            .setRightText(R.string.after_see,null)
            .show();
    }

}
